package yk.flutter.platelpr;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.hyperai.hyperlpr3.HyperLPR3;
import com.hyperai.hyperlpr3.bean.HyperLPRParameter;
import com.hyperai.hyperlpr3.bean.Plate;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

/**
 * 车牌识别Activity
 * 负责相机预览、拍照、闪光灯控制等功能
 */
public class PlateLprActivity extends Activity {

    private static final String TAG = "PlateLprActivity";
    private static final int REQUEST_CAMERA_PERMISSION = 200;

    // 相机方向映射
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    // UI组件
    private TextureView textureView;
    private TextView tvStatus;
    private ImageButton btnFlash;
    private ImageButton btnCapture;
    private Button btnNoPlate;
    private PlateFrameView plateFrameView;
    private FrameLayout cameraContainer;

    // 相机相关
    private String cameraId;
    private CameraDevice cameraDevice;
    private CameraCaptureSession cameraCaptureSessions;
    private CaptureRequest.Builder captureRequestBuilder;
    private Size imageDimension;
    private ImageReader imageReader;
    private Handler backgroundHandler;
    private HandlerThread backgroundThread;

    // 闪光灯状态
    private boolean isFlashOn = false;
    private boolean hasFlash = false;

    // 参数
    private int recogButtonType = 0; // 0: hidden, 1: noPlate, 2: manualInput
    private String title = "车牌识别";

    // 识别状态控制
    private volatile boolean isRecognizing = false;
    private volatile boolean isAutoRecognizing = false;
    private Handler autoRecognitionHandler;
    private Runnable autoRecognitionRunnable;
    private static final long AUTO_RECOGNITION_INTERVAL = 500; // 500毫秒间隔
    
    // 当前图片路径（用于手动拍照）
    private String currentImagePath = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plate_lpr);

        // 获取传入参数
        Intent intent = getIntent();
        if (intent != null) {
            recogButtonType = intent.getIntExtra("recogButtonType", 0);
            title = intent.getStringExtra("title");
            if (title == null)
                title = "车牌识别";
        }

        // 初始化HyperLPR3
        initHyperLPR3();

        initViews();
        setupListeners();

        // 检查闪光灯支持
        hasFlash = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        if (!hasFlash) {
            btnFlash.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化HyperLPR3车牌识别引擎
     */
    private void initHyperLPR3() {
        try {
            // 检查HyperLPR3是否已经初始化
            if (HyperLPR3.getInstance() == null) {
                Log.e(TAG, "HyperLPR3实例为空");
                return;
            }
            
            // 车牌识别算法配置参数
            HyperLPRParameter parameter = new HyperLPRParameter()
                .setNmsThreshold(0.92f);
                
            HyperLPR3.getInstance().init(this, parameter);
            boolean initResult = true; // init方法返回void，假设初始化成功
            if (initResult) {
                Log.d(TAG, "HyperLPR3初始化成功");
            } else {
                Log.e(TAG, "HyperLPR3初始化返回false");
            }
        } catch (UnsatisfiedLinkError e) {
            Log.e(TAG, "HyperLPR3 native库加载失败: " + e.getMessage());
            e.printStackTrace();
            // 显示错误提示并关闭Activity
            runOnUiThread(() -> {
                Toast.makeText(this, "车牌识别引擎初始化失败，请重新安装应用", Toast.LENGTH_LONG).show();
                finish();
            });
        } catch (Exception e) {
            Log.e(TAG, "HyperLPR3初始化异常: " + e.getMessage());
            e.printStackTrace();
            // 显示错误提示但不关闭Activity，允许用户继续使用其他功能
            runOnUiThread(() -> {
                Toast.makeText(this, "车牌识别功能可能不可用", Toast.LENGTH_SHORT).show();
            });
        }
    }

    /**
     * 初始化视图组件
     */
    private void initViews() {
        textureView = findViewById(R.id.texture_view);
        tvStatus = findViewById(R.id.tv_status);
        btnFlash = findViewById(R.id.btn_flash);
        btnCapture = findViewById(R.id.btn_capture);
        btnNoPlate = findViewById(R.id.btn_no_plate);
        plateFrameView = findViewById(R.id.plate_frame_view);
        cameraContainer = findViewById(R.id.camera_container);

        // 设置标题
        tvStatus.setText(title);

        // 设置按钮状态
        switch (recogButtonType) {
            case 1: // noPlate
                btnNoPlate.setVisibility(View.VISIBLE);
                btnNoPlate.setText("无牌车");
                break;
            case 2: // manualInput
                btnNoPlate.setVisibility(View.VISIBLE);
                btnNoPlate.setText("手动输入");
                break;
            default: // hidden
                btnNoPlate.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 闪光灯按钮
        btnFlash.setOnClickListener(v -> toggleFlash());

        // 拍照按钮
        btnCapture.setOnClickListener(v -> takePicture());

        // 无牌车/手动输入按钮
        btnNoPlate.setOnClickListener(v -> {
            // 点击时也需要拍照
            takePictureForCustomButton();
        });

        // TextureView监听器
        textureView.setSurfaceTextureListener(textureListener);
    }
    

    /**
     * TextureView监听器
     */
    private final TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(android.graphics.SurfaceTexture surface, int width, int height) {
            openCamera();
        }

        @Override
        public void onSurfaceTextureSizeChanged(android.graphics.SurfaceTexture surface, int width, int height) {
            // 不再需要
        }

        @Override
        public boolean onSurfaceTextureDestroyed(android.graphics.SurfaceTexture surface) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(android.graphics.SurfaceTexture surface) {
            // 纹理更新
        }
    };

    /**
     * 相机状态回调
     */
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            Log.d(TAG, "相机已打开");
            cameraDevice = camera;
            createCameraPreview();
        }

        @Override
        public void onDisconnected(CameraDevice camera) {
            cameraDevice.close();
        }

        @Override
        public void onError(CameraDevice camera, int error) {
            cameraDevice.close();
            cameraDevice = null;
        }
    };

    /**
     * 打开相机
     */
    private void openCamera() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA },
                    REQUEST_CAMERA_PERMISSION);
            return;
        }

        CameraManager manager = (CameraManager) getSystemService(CAMERA_SERVICE);
        Log.d(TAG, "正在打开相机");

        try {
            cameraId = manager.getCameraIdList()[0];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;
            
            // 获取支持的输出尺寸并选择合适的尺寸
            Size[] jpegSizes = map.getOutputSizes(ImageFormat.JPEG);
            imageDimension = chooseOptimalSize(jpegSizes); // 选择最接近4:3的尺寸

            // 调整预览视图的宽高比以匹配相机输出
            adjustAspectRatio(imageDimension.getWidth(), imageDimension.getHeight());

            // 创建ImageReader
            imageReader = ImageReader.newInstance(imageDimension.getWidth(), imageDimension.getHeight(),
                    ImageFormat.JPEG, 1);
            imageReader.setOnImageAvailableListener(readerListener, backgroundHandler);

            manager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "相机打开完成");
    }

    /**
     * 创建相机预览
     */
    protected void createCameraPreview() {
        try {
            Surface surface = new Surface(textureView.getSurfaceTexture());
            captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureRequestBuilder.addTarget(surface);
            
            // 将预览Surface和ImageReader的Surface都添加到会话中
            cameraDevice.createCaptureSession(Arrays.asList(surface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    if (null == cameraDevice) {
                        return;
                    }
                    cameraCaptureSessions = cameraCaptureSession;
                    updatePreview();
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Log.e(TAG, "相机会话配置失败");
                    Toast.makeText(PlateLprActivity.this, "相机配置失败", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            Log.e(TAG, "创建相机预览异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 更新预览
     */
    protected void updatePreview() {
        if (null == cameraDevice) {
            Log.e(TAG, "更新预览错误，返回");
            return;
        }
        if (null == cameraCaptureSessions) {
            Log.e(TAG, "相机会话为空，返回");
            return;
        }

        captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);

        // 设置闪光灯
        if (hasFlash) {
            captureRequestBuilder.set(CaptureRequest.FLASH_MODE,
                    isFlashOn ? CaptureRequest.FLASH_MODE_TORCH : CaptureRequest.FLASH_MODE_OFF);
        }

        try {
            cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, backgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Log.e(TAG, "相机会话已关闭: " + e.getMessage());
        }
    }

    /**
     * 拍照
     */
    protected void takePicture() {
        // 防止在识别过程中重复拍照
        if (isRecognizing) {
            Log.w(TAG, "正在识别中，请稍后再试");
            Toast.makeText(this, "正在识别中，请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 停止自动识别，进行手动拍照
        stopAutoRecognition();
        
        if (null == cameraDevice) {
            Log.e(TAG, "相机设备为空，无法拍照");
            return;
        }
        
        if (null == cameraCaptureSessions) {
            Log.e(TAG, "相机会话为空，无法拍照");
            return;
        }
        
        if (null == imageReader) {
            Log.e(TAG, "ImageReader为空，无法拍照");
            return;
        }

        tvStatus.setText("正在拍照...");
        btnCapture.setEnabled(false);

        try {
            CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(imageReader.getSurface());
            captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);

            // 设置拍照时的闪光灯
            if (hasFlash && isFlashOn) {
                captureBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE);
            }

            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));

            cameraCaptureSessions.capture(captureBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request,
                        @NonNull TotalCaptureResult result) {
                    super.onCaptureCompleted(session, request, result);
                    Log.d(TAG, "手动拍照完成");
                }
            }, backgroundHandler);

        } catch (CameraAccessException e) {
            Log.e(TAG, "拍照时相机访问异常: " + e.getMessage());
            e.printStackTrace();
            runOnUiThread(() -> {
                btnCapture.setEnabled(true);
                tvStatus.setText("拍照失败");
                Toast.makeText(PlateLprActivity.this, "拍照失败", Toast.LENGTH_SHORT).show();
                startAutoRecognition();
            });
        } catch (IllegalStateException e) {
            Log.e(TAG, "拍照时状态异常: " + e.getMessage());
            e.printStackTrace();
            runOnUiThread(() -> {
                btnCapture.setEnabled(true);
                tvStatus.setText("拍照失败");
                Toast.makeText(PlateLprActivity.this, "拍照失败，请重试", Toast.LENGTH_SHORT).show();
                startAutoRecognition();
            });
        }
    }

    /**
     * 图片读取监听器
     */
    private final ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            Image image = null;
            try {
                image = reader.acquireLatestImage();
                if (image != null) {
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    
                    if (backgroundHandler != null) {
                        backgroundHandler.post(() -> {
                            try {
                                String imagePath = saveImageToFile(bytes);
                                runOnUiThread(() -> {
                                    if (!isFinishing() && !isDestroyed()) {
                                        tvStatus.setText("正在识别车牌...");
                                        backgroundHandler.post(() -> {
                                            handleRecognition(imagePath);
                                        });
                                    }
                                });
                            } catch (Exception e) {
                                Log.e(TAG, "后台处理图片异常: " + e.getMessage());
                                e.printStackTrace();
                                runOnUiThread(() -> {
                                    if (!isFinishing() && !isDestroyed()) {
                                        btnCapture.setEnabled(true);
                                        tvStatus.setText("图片处理失败");
                                        Toast.makeText(PlateLprActivity.this, "图片处理失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "处理图片时异常: " + e.getMessage());
                e.printStackTrace();
                runOnUiThread(() -> {
                    if (!isFinishing() && !isDestroyed()) {
                        btnCapture.setEnabled(true);
                        tvStatus.setText("图片处理失败");
                        Toast.makeText(PlateLprActivity.this, "图片处理失败", Toast.LENGTH_SHORT).show();
                    }
                });
            } finally {
                if (image != null) {
                    image.close();
                }
            }
        }
    };

    /**
     * 将Bitmap的尺寸调整到最长边为1280px（模拟720p），并保持宽高比
     * @param source 原始Bitmap
     * @return 调整尺寸后的Bitmap
     */
    private Bitmap resizeBitmapTo720P(Bitmap source) {
        if (source == null) return null;
        int maxEdge = 1280;
        int width = source.getWidth();
        int height = source.getHeight();

        if (width <= maxEdge && height <= maxEdge) {
            return source; // 如果图片已经小于目标尺寸，则不缩放
        }

        int newWidth, newHeight;
        if (width > height) {
            newWidth = maxEdge;
            newHeight = (int) (height * ( (float) maxEdge / width));
        } else {
            newHeight = maxEdge;
            newWidth = (int) (width * ( (float) maxEdge / height));
        }

        return Bitmap.createScaledBitmap(source, newWidth, newHeight, true);
    }

    /**
     * 保存图片到文件（包含压缩逻辑）
     */
    private String saveImageToFile(byte[] bytes) {
        try {
            // 1. 解码为Bitmap
            Bitmap originalBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            if (originalBitmap == null) {
                Log.e(TAG, "无法将byte数组解码为Bitmap");
                return null;
            }

            // 2. 调整尺寸
            Bitmap resizedBitmap = resizeBitmapTo720P(originalBitmap);

            // 3. 保存调整尺寸后的Bitmap
            File picturesDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "PlateLpr");
            if (!picturesDir.exists()) {
                picturesDir.mkdirs();
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "IMG_" + timeStamp + ".jpg";
            File file = new File(picturesDir, fileName);

            FileOutputStream output = new FileOutputStream(file);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, output); // 使用90%质量压缩
            output.flush();
            output.close();

            // 4. 释放内存
            if (originalBitmap != resizedBitmap) {
                originalBitmap.recycle();
            }
            resizedBitmap.recycle();

            currentImagePath = file.getAbsolutePath();
            return currentImagePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存Bitmap到文件（包含压缩逻辑）
     */
    private String saveBitmapToFile(Bitmap bitmap) {
        if (bitmap == null || bitmap.isRecycled()) {
            Log.e(TAG, "Bitmap无效，无法保存");
            return null;
        }
        
        try {
            // 1. 调整尺寸
            // 注意：自动识别的Bitmap是预览帧，直接缩放会影响显示，所以先创建一个副本
            Bitmap resizedBitmap = resizeBitmapTo720P(bitmap.copy(bitmap.getConfig(), true));

            // 2. 保存调整尺寸后的Bitmap
            File picturesDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "PlateLpr");
            if (!picturesDir.exists()) {
                picturesDir.mkdirs();
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "AUTO_" + timeStamp + ".jpg";
            File file = new File(picturesDir, fileName);

            FileOutputStream output = new FileOutputStream(file);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, output);
            output.flush();
            output.close();

            // 3. 释放新创建的Bitmap内存
            resizedBitmap.recycle();

            Log.d(TAG, "自动识别图片已保存: " + file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (Exception e) {
            Log.e(TAG, "保存Bitmap异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当前图片路径
     */
    private String getCurrentImagePath() {
        return currentImagePath;
    }

    /**
     * 处理手动拍照识别
     */
    private void handleRecognition(String imagePath) {
        if (isRecognizing) {
            Log.w(TAG, "正在识别中，忽略重复请求");
            return;
        }
        
        isRecognizing = true;
        
        try {
            if (imagePath != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                if (bitmap != null) {
                    performPlateRecognition(bitmap, false); // false表示手动识别
                    return; 
                } else {
                    Log.e(TAG, "无法读取图片文件: " + imagePath);
                    handleRecognitionResult("error", 0.0f, imagePath);
                }
            } else {
                Log.w(TAG, "图片路径为空");
                handleRecognitionResult("error", 0.0f, null);
            }
        } catch (Exception e) {
            Log.e(TAG, "读取图片异常: " + e.getMessage());
            e.printStackTrace();
            handleRecognitionResult("error", 0.0f, imagePath);
        } finally {
            isRecognizing = false;
        }
    }

    /**
     * 处理识别的最终结果并返回
     */
    private void handleRecognitionResult(String plateNumber, float confidence, String imagePath) {
        runOnUiThread(() -> {
            if (!isFinishing() && !isDestroyed()) {
                Intent resultIntent = new Intent();
                resultIntent.putExtra("plateNumber", plateNumber);
                resultIntent.putExtra("confidence", confidence);
                resultIntent.putExtra("imagePath", imagePath);
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }

    private byte[] getPixelsRGBA(Bitmap image) {
        if (image == null || image.isRecycled()) {
            Log.e(TAG, "Bitmap为空或已回收");
            return null;
        }
        
        try {
            int width = image.getWidth();
            int height = image.getHeight();
            
            int[] pixels = new int[width * height];
            image.getPixels(pixels, 0, width, 0, 0, width, height);
            
            byte[] bgraBytes = new byte[width * height * 4];
            for (int i = 0; i < pixels.length; i++) {
                int pixel = pixels[i];
                int index = i * 4;
                
                bgraBytes[index] = (byte) (pixel & 0xFF);         // B
                bgraBytes[index + 1] = (byte) ((pixel >> 8) & 0xFF);  // G
                bgraBytes[index + 2] = (byte) ((pixel >> 16) & 0xFF); // R
                bgraBytes[index + 3] = (byte) ((pixel >> 24) & 0xFF); // A
            }
            
            return bgraBytes;
            
        } catch (Exception e) {
            Log.e(TAG, "转换图片数据异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 为自定义按钮（无牌车/手动输入）进行拍照并返回结果
     */
    private void takePictureForCustomButton() {
        ImageReader.OnImageAvailableListener customButtonListener = reader -> {
            Image image = null;
            try {
                image = reader.acquireLatestImage();
                if (image != null) {
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);

                    String imagePath = saveImageToFile(bytes);

                    String plateResult = "";
                    if (recogButtonType == 1) {
                        plateResult = "noplate";
                    } else if (recogButtonType == 2) {
                        plateResult = "input";
                    }
                    handleCustomButtonResult(plateResult, imagePath);
                }
            } catch (Exception e) {
                Log.e(TAG, "处理自定义按钮图片时异常: " + e.getMessage());
                e.printStackTrace();
                handleCustomButtonResult(recogButtonType == 1 ? "noplate" : "input", null);
            } finally {
                if (image != null) {
                    image.close();
                }
                imageReader.setOnImageAvailableListener(readerListener, backgroundHandler);
            }
        };

        imageReader.setOnImageAvailableListener(customButtonListener, backgroundHandler);
        takePicture();
    }

    /**
     * 处理自定义按钮点击后的结果
     */
    private void handleCustomButtonResult(String plateNumber, String imagePath) {
        runOnUiThread(() -> {
            if (!isFinishing() && !isDestroyed()) {
                Intent resultIntent = new Intent();
                resultIntent.putExtra("plateNumber", plateNumber);
                resultIntent.putExtra("confidence", 1.0f); // 自定义按钮点击，置信度为1
                resultIntent.putExtra("imagePath", imagePath);
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }

    /**
     * 切换闪光灯
     */
    private void toggleFlash() {
        if (!hasFlash)
            return;

        isFlashOn = !isFlashOn;
        btnFlash.setImageResource(isFlashOn ? R.drawable.ic_flash_on : R.drawable.ic_flash_off);
        updatePreview();
    }

    /**
     * 关闭相机
     */
    private void closeCamera() {
        if (null != cameraDevice) {
            cameraDevice.close();
            cameraDevice = null;
        }
        if (null != imageReader) {
            imageReader.close();
            imageReader = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(PlateLprActivity.this, "需要相机权限才能使用此功能", Toast.LENGTH_LONG).show();
                finish();
            } else {
                openCamera();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        startBackgroundThread();
        if (textureView.isAvailable()) {
            openCamera();
        } else {
            textureView.setSurfaceTextureListener(textureListener);
        }
        startAutoRecognition();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause");
        stopAutoRecognition();
        closeCamera();
        stopBackgroundThread();
        super.onPause();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Activity销毁");
    }

    /**
     * 启动后台线程
     */
    protected void startBackgroundThread() {
        backgroundThread = new HandlerThread("Camera Background");
        backgroundThread.start();
        backgroundHandler = new Handler(backgroundThread.getLooper());
    }

    /**
     * 停止后台线程
     */
    protected void stopBackgroundThread() {
        backgroundThread.quitSafely();
        try {
            backgroundThread.join();
            backgroundThread = null;
            backgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动自动识别
     */
    private void startAutoRecognition() {
        if (autoRecognitionHandler == null) {
            autoRecognitionHandler = new Handler();
        }
        
        autoRecognitionRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isAutoRecognizing && !isRecognizing && textureView != null && textureView.isAvailable()) {
                    performAutoRecognition();
                }
                if (autoRecognitionHandler != null) {
                    autoRecognitionHandler.postDelayed(this, AUTO_RECOGNITION_INTERVAL);
                }
            }
        };
        
        autoRecognitionHandler.postDelayed(autoRecognitionRunnable, AUTO_RECOGNITION_INTERVAL);
        Log.d(TAG, "自动识别已启动");
    }

    /**
     * 停止自动识别
     */
    private void stopAutoRecognition() {
        if (autoRecognitionHandler != null && autoRecognitionRunnable != null) {
            autoRecognitionHandler.removeCallbacks(autoRecognitionRunnable);
            autoRecognitionHandler = null;
            autoRecognitionRunnable = null;
        }
        isAutoRecognizing = false;
        Log.d(TAG, "自动识别已停止");
    }

    /**
     * 执行自动识别
     */
    private void performAutoRecognition() {
        if (textureView == null || !textureView.isAvailable()) {
            return;
        }
        
        try {
            Bitmap bitmap = textureView.getBitmap();
            if (bitmap != null && !bitmap.isRecycled()) {
                if (backgroundHandler != null) {
                    backgroundHandler.post(() -> {
                        try {
                            performPlateRecognition(bitmap, true); // true表示自动识别
                        } catch (Exception e) {
                            Log.e(TAG, "自动识别异常: " + e.getMessage());
                            e.printStackTrace();
                        } finally {
                            isAutoRecognizing = false;
                        }
                    });
                }
            } else {
                isAutoRecognizing = false;
            }
        } catch (Exception e) {
            Log.e(TAG, "获取预览帧异常: " + e.getMessage());
            e.printStackTrace();
            isAutoRecognizing = false;
        }
    }

    /**
     * 执行车牌识别
     * @param bitmap 要识别的图片
     * @param isAutoMode 是否为自动识别模式
     */
    private void performPlateRecognition(Bitmap bitmap, boolean isAutoMode) {
        if (bitmap == null || bitmap.isRecycled()) {
            Log.w(TAG, "Bitmap无效，跳过识别");
            return;
        }

        Bitmap bitmapToRecognize = null;
        try {
            RectF frameRect = plateFrameView.getFrameRect();
            if (frameRect != null && !frameRect.isEmpty()) {
                Rect cropRect = new Rect();
                if (isAutoMode) {
                    cropRect.left = (int) frameRect.left;
                    cropRect.top = (int) frameRect.top;
                    cropRect.right = (int) frameRect.right;
                    cropRect.bottom = (int) frameRect.bottom;
                } else {
                    float scaleX = (float) bitmap.getWidth() / textureView.getWidth();
                    float scaleY = (float) bitmap.getHeight() / textureView.getHeight();
                    cropRect.left = (int) (frameRect.left * scaleX);
                    cropRect.top = (int) (frameRect.top * scaleY);
                    cropRect.right = (int) (frameRect.right * scaleX);
                    cropRect.bottom = (int) (frameRect.bottom * scaleY);
                }

                cropRect.left = Math.max(0, cropRect.left);
                cropRect.top = Math.max(0, cropRect.top);
                cropRect.right = Math.min(bitmap.getWidth(), cropRect.right);
                cropRect.bottom = Math.min(bitmap.getHeight(), cropRect.bottom);

                if (cropRect.width() > 0 && cropRect.height() > 0) {
                    bitmapToRecognize = Bitmap.createBitmap(bitmap, cropRect.left, cropRect.top, cropRect.width(), cropRect.height());
                    Log.d(TAG, "已裁剪图片进行识别: " + cropRect.width() + "x" + cropRect.height());
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "裁剪图片失败，将使用全图识别", e);
        }

        if (bitmapToRecognize == null) {
            bitmapToRecognize = bitmap;
        }

        try {
            if (HyperLPR3.getInstance() == null) {
                Log.e(TAG, "HyperLPR3实例不可用");
                if (!isAutoMode) {
                    handleRecognitionResult("error", 0.0f, getCurrentImagePath());
                }
                return;
            }

            int width = bitmapToRecognize.getWidth();
            int height = bitmapToRecognize.getHeight();

            byte[] imageData = getPixelsRGBA(bitmapToRecognize);

            if (imageData != null && imageData.length > 0) {
                try {
                    Plate[] results = HyperLPR3.getInstance().plateRecognition(imageData, height, width,
                            HyperLPR3.CAMERA_ROTATION_0, HyperLPR3.STREAM_BGRA);

                    if (results != null && results.length > 0) {
                        Plate bestResult = results[0];
                        float threshold = isAutoMode ? 0.9f : 0.7f;
                        if (bestResult.getType() != HyperLPR3.PLATE_TYPE_UNKNOWN && bestResult.getConfidence() > threshold) {
                            String plateNumber = bestResult.getCode();
                            float confidence = bestResult.getConfidence();
                            Log.d(TAG, (isAutoMode ? "自动" : "手动") + "识别结果: " + plateNumber + ", 置信度: " + confidence);
                            
                            if (isAutoMode) {
                                stopAutoRecognition();
                                String imagePath = saveBitmapToFile(bitmap);
                                handleRecognitionResult(plateNumber, confidence, imagePath);
                            } else {
                                handleRecognitionResult(plateNumber, confidence, getCurrentImagePath());
                            }
                        } else {
                           if (!isAutoMode) handleRecognitionResult("error", 0.0f, getCurrentImagePath());
                        }
                    } else {
                        Log.d(TAG, (isAutoMode ? "自动" : "手动") + "识别未检测到车牌");
                        if (!isAutoMode) {
                            handleRecognitionResult("error", 0.0f, getCurrentImagePath());
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "HyperLPR3识别调用异常: " + e.getMessage());
                    e.printStackTrace();
                    if (!isAutoMode) {
                        handleRecognitionResult("error", 0.0f, getCurrentImagePath());
                    }
                }
            } else {
                Log.e(TAG, "图片数据转换失败");
                if (!isAutoMode) {
                    handleRecognitionResult("error", 0.0f, getCurrentImagePath());
                }
            }

        } catch (Exception e) {
            Log.e(TAG, (isAutoMode ? "自动" : "手动") + "识别异常: " + e.getMessage());
            e.printStackTrace();
            if (!isAutoMode) {
                handleRecognitionResult("error", 0.0f, getCurrentImagePath());
            }
        } finally {
            if (bitmapToRecognize != null && bitmapToRecognize != bitmap) {
                bitmapToRecognize.recycle();
            }
            if (!isAutoMode && bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
    }

    /**
     * 选择最佳的预览尺寸
     */
    private Size chooseOptimalSize(Size[] choices) {
        Size optimalSize = null;
        double targetRatio = 4.0 / 3.0;
        
        for (Size size : choices) {
            double ratio = (double) size.getWidth() / size.getHeight();
            if (Math.abs(ratio - targetRatio) < 0.05) {
                if (optimalSize == null || size.getWidth() * size.getHeight() > optimalSize.getWidth() * optimalSize.getHeight()) {
                    optimalSize = size;
                }
            }
        }

        if (optimalSize == null) {
            Log.w(TAG, "未找到接近4:3的预览尺寸，将选择最大尺寸");
            for (Size size : choices) {
                if (optimalSize == null || size.getWidth() * size.getHeight() > optimalSize.getWidth() * optimalSize.getHeight()) {
                    optimalSize = size;
                }
            }
        }

        Log.d(TAG, "选择的预览尺寸: " + optimalSize.getWidth() + "x" + optimalSize.getHeight());
        return optimalSize;
    }

    /**
     * 调整TextureView的宽高比
     */
    private void adjustAspectRatio(int cameraWidth, int cameraHeight) {
        float ratio = (float) cameraWidth / cameraHeight;

        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int newHeight = (int) (screenWidth * ratio);

        runOnUiThread(() -> {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) textureView.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = newHeight;
            layoutParams.gravity = android.view.Gravity.CENTER;
            textureView.setLayoutParams(layoutParams);
        });
    }

    @Override
    public void onBackPressed() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("plateNumber", "back");
        resultIntent.putExtra("confidence", 0.0f);
        resultIntent.putExtra("imagePath", "");
        setResult(RESULT_OK, resultIntent);
        finish();
        super.onBackPressed();
    }
}